package com.focusai.efairy.ui.activity.warn;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.util.Pair;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.model.request.PostInputAlarmRequest;
import com.focusai.efairy.model.warn.UpLoadAlarmItem;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerViewHolder;
import com.focusai.efairy.ui.adapter.warn.SelectPaireAdapter;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.ui.iview.IUpLoadFileListView;
import com.focusai.efairy.ui.presenter.UpLoadFilePresenter;
import com.focusai.efairy.ui.widget.InputGirdImageView;
import com.focusai.efairy.utils.ActivityUtils;
import com.focusai.efairy.utils.ImageUtils;
import com.focusai.efairy.utils.permission.PermissionListener;
import com.focusai.efairy.utils.permission.PermissionUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * Created by luo_guangwen on 2017/10/12.
 */

public class InputAlarmActivity extends SwipeBackBaseActivity implements View.OnClickListener {
    public final static String KEY_MSG_ITEMS = "key_msg_items"; //打开图片预览
    public final static String KEY_DEV_ID = "key_dev_item";

    private final static int REQUEST_CODE_ALBUM = 100; //打开相册回调
    private final static int REQUEST_CODE_PREVIEW = 101; //打开图片预览
    private final static int EVENT_UPLOAD = 102;
    private final static int EVENT_UPLOAD_FILE_SUCCUSS = 103;
    private final static int EVENT_UPLOAD_FILE_FAIL = 104;
    private InputGirdImageView girdImageView;
    private TextView textAlarmType;
    private TextView textDanger;
    private TextView textHandDo;
    private ArrayList<String> fileImageList;
    private ArrayList<Long> msgItems;
    List<Pair<Integer, String>> typeList;
    private int currentTypeId = 0;
    private long deviceId = 0;
    private UpLoadFilePresenter upLoadFilePresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_input_alarm);
        initView();
        initData();
        bindEvents();
        setDefaultValues();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.upload).setTitle(R.string.upload);
        MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            if (TextUtils.isEmpty(textAlarmType.getText().toString())){
                showToast("请选择报警类型");
                return super.onOptionsItemSelected(item);
            }
            getProcHandler().sendEmptyMessage(EVENT_UPLOAD);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView() {
        girdImageView = findView(R.id.grid_img_view);
        textAlarmType = findView(R.id.text_maintain_type);
        textDanger = findView(R.id.text_hidden_danger);
        textHandDo = findView(R.id.text_do_complete);
    }

    private void initData() {
        if (getIntent() != null) {
            msgItems = (ArrayList<Long>) getIntent().getSerializableExtra(KEY_MSG_ITEMS);
            deviceId = getIntent().getLongExtra(KEY_DEV_ID, 0);
        }
        if (msgItems == null || deviceId == 0) {
            showToast("请选择需要处理的设备消息");
            finish();
        }
        typeList = new ArrayList<>();
        typeList.add(new Pair<Integer, String>(1, "火警"));
        typeList.add(new Pair<Integer, String>(2, "预警"));
        typeList.add(new Pair<Integer, String>(3, "故障"));
    }

    @Override
    protected void bindEvents() {
        setCenterTitleName("新增报警处理");
        findView(R.id.ll_maintain_type).setOnClickListener(this);
        findView(R.id.ll_hidden_danger).setOnClickListener(this);
        findView(R.id.ll_do_complete).setOnClickListener(this);
        girdImageView.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerViewHolder holder) {
                String path = girdImageView.getItem(holder);
                if (InputGirdImageView.LAST.equals(path)) {
                    openPhotoPickerActivity(girdImageView.DEFAUTECOUNT - fileImageList.size());
                } else {
                    ActivityUtils.openPhotoPagerActivity(InputAlarmActivity.this, REQUEST_CODE_PREVIEW, girdImageView.getPosition(holder), fileImageList, true);
                }
            }
        });
    }

    @Override
    protected boolean useHandleThread() {
        return true;
    }

    @Override
    protected boolean procHandlerCallback(Message msg) {
        switch (msg.what) {
            case EVENT_UPLOAD:
                upLoadFile(fileImageList);
                break;
            default:
                break;
        }
        return super.procHandlerCallback(msg);
    }

    @Override
    protected boolean uiHandlerCallback(Message msg) {
        switch (msg.what) {
            case EVENT_UPLOAD_FILE_SUCCUSS:
                upLoadData((List<String>) msg.obj);
                break;
            case EVENT_UPLOAD_FILE_FAIL:
                closeSingleDialog();
                showToast("上传图片失败");
                break;
            default:
                break;
        }
        return super.uiHandlerCallback(msg);
    }

    @Override
    protected void setDefaultValues() {
        fileImageList = new ArrayList<>();
        upLoadFilePresenter = new UpLoadFilePresenter();
    }

    /**
     * 打开相册
     */
    private void openPhotoPickerActivity(final int count) {
        checkPermission(PermissionUtil.PERMISSION_STORAGE, new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, List<String> grantedList) {
                PhotoPickerIntent intent = new PhotoPickerIntent(getContext());
                intent.setPhotoCount(count);
                intent.setShowCamera(false);
                startActivityForResult(intent, REQUEST_CODE_ALBUM);
            }

            @Override
            public void onFailed(int requestCode, List<String> deniedList) {
                showToast("应用没读SD卡权限");
            }
        }, Manifest.permission.READ_EXTERNAL_STORAGE);

    }

    private void showDangerDialog() {
        AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                textDanger.setText(R.string.yes);
            }
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                textDanger.setText(R.string.no);
            }
        });

        dialog.setCancelable(true);
        dialog.setMessage(getString(R.string.no_hidden_danger));
        dialog.show();
    }

    private void showHandDoDialog() {
        AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                textHandDo.setText(R.string.yes);
            }
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                textHandDo.setText(R.string.no);
            }
        });

        dialog.setCancelable(true);
        dialog.setMessage(getString(R.string.do_in_scene));
        dialog.show();
    }

    private void openSelecteAlarmType() {
        AlertDialog.Builder builder = new AlertDialog.Builder(InputAlarmActivity.this);
        SelectPaireAdapter locationAdapter = new SelectPaireAdapter(typeList);
        builder.setAdapter(locationAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                currentTypeId = typeList.get(which).first;
                textAlarmType.setText(typeList.get(which).second);
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ALBUM:
                    ArrayList<String> arrayList = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    if (arrayList != null) {
                        fileImageList.addAll(arrayList);
                        girdImageView.refreshData(fileImageList);
                    }
                    break;
                case REQUEST_CODE_PREVIEW:
                    ArrayList<String> arrayList1 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    if (arrayList1 != null) {
                        fileImageList.clear();
                        fileImageList.addAll(arrayList1);
                        girdImageView.refreshData(fileImageList);
                    }
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void upLoadData(List<String> urlList) {
        if (msgItems == null || msgItems.size() == 0)
            return;
        UpLoadAlarmItem item = new UpLoadAlarmItem();
        item.efairyalarmrecord_alarm_id = currentTypeId;
        item.efairyalarmrecord_is_handle = 0;
        item.efairyalarmrecord_is_insite_handle = 0;
        item.efairydevice_id = deviceId;
        item.efairyalarmrecord_content = girdImageView.getContentText();
        if (textHandDo.getText().toString().equals(getResources().getString(R.string.yes))) {
            item.efairyalarmrecord_is_insite_handle = 1;
        }
        if (textDanger.getText().toString().equals(getResources().getString(R.string.yes))) {
            item.efairyalarmrecord_is_handle = 1;
        }
        item.efairydevicemsg_id_list = new ArrayList<>();
//        for (MsgItem msgItem : msgItems) {
//            item.efairydevicemsg_id_list.add(msgItem.get_id());
//        }
        item.efairydevicemsg_id_list = msgItems;
        item.efairyalarmrecord_imgurl_list = (urlList == null ? new ArrayList<String>(0) : urlList);
        HttpManager.getInstance().sendRequest(new PostInputAlarmRequest(item, new Response.Listener<String>() {
            @Override
            protected void onSuccess(String response) {
                closeSingleDialog();
                showToast("报警处理成功");
                setResult(RESULT_OK);
                finish();
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
                showToast("上传数据失败");
            }
        }));
    }

    private void upLoadFile(List<String> fileOldPath) {
        showProgressDialog("正在上传数据..");
        if (fileOldPath == null || fileOldPath.size() == 0) {
            Message msg = getUiHandler().obtainMessage();
            msg.what = EVENT_UPLOAD_FILE_SUCCUSS;
            msg.obj = new ArrayList<>();
            getUiHandler().sendMessage(msg);
            return;
        }
        List<String> newImagePaths = new ArrayList<>();
        for (String oldPath : fileOldPath) {
            newImagePaths.add(ImageUtils.saveCompressImageFile(oldPath));
        }
        upLoadFilePresenter.upLaodFiles(newImagePaths, 0, new IUpLoadFileListView() {
            @Override
            public void onUpLoadFileSeccuss(LinkedHashMap<String, String> urlMap) {
                Iterator it = urlMap.entrySet().iterator();
                List<String> urlList = new ArrayList<>();
                while (it.hasNext()) {
                    urlList.add((String) ((Map.Entry) it.next()).getKey());
                }
                Message msg = getUiHandler().obtainMessage();
                msg.what = EVENT_UPLOAD_FILE_SUCCUSS;
                msg.obj = urlList;
                getUiHandler().sendMessage(msg);
            }

            @Override
            public void onUpLoadFileFail(String errormsg) {
                getUiHandler().sendEmptyMessage(EVENT_UPLOAD_FILE_FAIL);
            }

            @Override
            public void onUpLoaditemSussuss(String url, int position, int count) {
                showProgressDialog("正在上传图片" + position + "/" + count);
            }
        });
    }

    private void showProgressDialog(String text) {
        showSingleDialog(text);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_maintain_type:
                openSelecteAlarmType();
                break;
            case R.id.ll_hidden_danger:
                showDangerDialog();
                break;
            case R.id.ll_do_complete:
                showHandDoDialog();
                break;
            default:
                break;
        }
    }
}
